package com.sangcomz.fishbun.ui.picker;

import com.sangcomz.fishbun.ui.picker.model.AlbumData;
import com.sangcomz.fishbun.ui.picker.model.PickerListItem;
import com.sangcomz.fishbun.ui.picker.model.PickerRepository;
import com.sangcomz.fishbun.ui.picker.model.PickerViewData;
import com.sangcomz.fishbun.util.UiHandler;
import com.sangcomz.fishbun.util.future.CallableFutureTask;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PickerPresenter implements PickerContract.Presenter {

    private PickerContract.View pickerView;
    private PickerRepository pickerRepository;
    private UiHandler uiHandler;
    private CallableFutureTask<List<Uri>> imageListFuture = null;
    private CallableFutureTask<String> dirPathFuture = null;

    public PickerPresenter(PickerContract.View pickerView, PickerRepository pickerRepository, UiHandler uiHandler) {
        this.pickerView = pickerView;
        this.pickerRepository = pickerRepository;
        this.uiHandler = uiHandler;
    }

    @Override
    public void takePicture() {
        if (pickerRepository.getPickerAlbumData() == null) {
            return;
        }
        AlbumData albumData = pickerRepository.getPickerAlbumData();
        if (albumData.getAlbumId() == 0) {
            if (pickerRepository.getDefaultSavePath() != null) {
                pickerView.takePicture(pickerRepository.getDefaultSavePath());
            }
        } else {
            dirPathFuture = pickerRepository.getDirectoryPath(albumData.getAlbumId());
            if (dirPathFuture != null) {
                dirPathFuture.execute(new CallableFutureTask.FutureCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        pickerView.takePicture(result);
                    }
                });
            }
        }
    }

    @Override
    public List<Uri> getAddedImagePathList() {
        return pickerRepository.getAddedPathList();
    }

    @Override
    public void addAddedPath(Uri addedImagePath) {
        pickerRepository.addAddedPath(addedImagePath);
    }

    @Override
    public void addAllAddedPath(List<Uri> addedImagePathList) {
        pickerRepository.addAllAddedPath(addedImagePathList);
    }

    @Override
    public void release() {
        if (dirPathFuture != null) {
            dirPathFuture.cancel(true);
        }
        if (imageListFuture != null) {
            imageListFuture.cancel(true);
        }
    }

    @Override
    public void successTakePicture(Uri addedImagePath) {
        addAddedPath(addedImagePath);
        updatePickerListItem();
    }

    @Override
    public void getPickerListItem() {
        if (pickerRepository.getPickerAlbumData() == null) {
            return;
        }
        AlbumData albumData = pickerRepository.getPickerAlbumData();
        imageListFuture = getAllMediaThumbnailsPath(albumData.getAlbumId(), false);
        imageListFuture.execute(new CallableFutureTask.FutureCallback<List<Uri>>() {
            @Override
            public void onSuccess(List<Uri> result) {
                onSuccessAllMediaThumbnailsPath(result);
            }
        });
    }

    @Override
    public void transImageFinish() {
        if (pickerRepository.getPickerAlbumData() == null) {
            return;
        }
        AlbumData albumData = pickerRepository.getPickerAlbumData();
        pickerView.takeANewPictureWithFinish(albumData.getAlbumPosition(),pickerRepository.getAddedPathList());
    }

    @Override
    public void getDesignViewData() {
        PickerViewData viewData = pickerRepository.getPickerViewData();
        pickerView.initToolBar(viewData);
        pickerView.initRecyclerView(viewData);
        setToolbarTitle();
    }

    @Override
    public void onClickThumbCount(int position) {
        changeImageStatus(position);
    }

    @Override
    public void onClickImage(int position) {
        if (pickerRepository.useDetailView()) {
            pickerView.showDetailView(getImagePosition(position));
        } else {
            changeImageStatus(position);
        }
    }

    @Override
    public void onDetailImageActivityResult() {
        PickerViewData pickerViewData = pickerRepository.getPickerViewData();
        if (pickerRepository.isLimitReached() && pickerViewData.isAutomaticClose()) {
            finish();
        } else {
            getPickerListItem();
        }
    }

    @Override
    public void getPickerMenuViewData(PickerMenuViewDataCallback callback) {
        callback.callback(pickerRepository.getPickerMenuViewData());
    }

    @Override
    public void onClickMenuDone() {
        int selectedCount = pickerRepository.getSelectedImageList().size();

        if (selectedCount == 0) {
            pickerView.showNothingSelectedMessage(pickerRepository.getMessageNotingSelected());
        } else if (selectedCount < pickerRepository.getMinCount()) {
            pickerView.showMinimumImageMessage(pickerRepository.getMinCount());
        } else {
            pickerView.finishActivity();
        }
    }

    @Override
    public void onClickMenuAllDone() {
        List<Uri> pickerImages = pickerRepository.getPickerImages();
        for (Uri uri : pickerImages) {
            if (pickerRepository.isLimitReached()) {
                break;
            }
            if (pickerRepository.isNotSelectedImage(uri)) {
                pickerRepository.selectImage(uri);
            }
        }
        pickerView.finishActivity();
    }

    @Override
    public void onSuccessTakePicture() {
        pickerView.onSuccessTakePicture();
    }

    private CallableFutureTask<List<Uri>> getAllMediaThumbnailsPath(long albumId, boolean clearCache) {
        return pickerRepository.getAllBucketImageUri(albumId, clearCache);
    }

    private void onSuccessAllMediaThumbnailsPath(List<Uri> imageUriList) {
        pickerRepository.setCurrentPickerImageList(imageUriList);

        PickerViewData viewData = pickerRepository.getPickerViewData();
        List<Uri> selectedImageList = pickerRepository.getSelectedImageList();
        List<PickerListItem> pickerList = new ArrayList<>();

        if (pickerRepository.hasCameraInPickerPage()) {
//            pickerList.add(PickerListItem.Camera);
        }

        for (Uri uri : imageUriList) {
            PickerListItem.Image image = new PickerListItem.Image(uri, selectedImageList.indexOf(uri), viewData);
            pickerList.add(image);
        }

        uiHandler.run(new UiHandler.RunUIThread() {
            @Override
            public void run() {
                pickerView.showImageList(pickerList,pickerRepository.getImageAdapter(),pickerRepository.hasCameraInPickerPage());
                setToolbarTitle();
            }
        });
    }

    private void updatePickerListItem() {
        if (pickerRepository.getPickerAlbumData() == null) {
            return;
        }
        AlbumData albumData = pickerRepository.getPickerAlbumData();
        imageListFuture = getAllMediaThumbnailsPath(albumData.getAlbumId(), true);
        imageListFuture.execute(new CallableFutureTask.FutureCallback<List<Uri>>() {
            @Override
            public void onSuccess(List<Uri> result) {
                onSuccessAllMediaThumbnailsPath(result);
            }
        });
    }

    private void setToolbarTitle() {
        String albumName = "";
        if (pickerRepository.getPickerAlbumData() != null && pickerRepository.getPickerAlbumData().getAlbumName() != null) {
            albumName = pickerRepository.getPickerAlbumData().getAlbumName();
        }
        pickerView.setToolbarTitle(pickerRepository.getPickerViewData(),
                pickerRepository.getSelectedImageList().size(),
                albumName);
    }

    private void changeImageStatus(int position) {
        int imagePosition = getImagePosition(position);
        Uri imageUri = pickerRepository.getPickerImage(imagePosition);
        if (pickerRepository.isNotSelectedImage(imageUri)) {
            selectImage(position, imageUri);
        } else {
            unselectImage(position, imageUri);
        }
    }

    private void selectImage(int position, Uri imageUri) {
        if (pickerRepository.isLimitReached()) {
            pickerView.showLimitReachedMessage(pickerRepository.getMessageLimitReached());
            return;
        }
        pickerRepository.selectImage(imageUri);
        if (pickerRepository.checkForFinish()) {
            finish();
        } else {
            onCheckStateChange(position, imageUri);
            setToolbarTitle();
        }
    }

    private void unselectImage(int position, Uri imageUri) {
        pickerRepository.unselectImage(imageUri);
        onCheckStateChange(position, imageUri);
        setToolbarTitle();
    }

    private int getImagePosition(int position) {
        //TODO 暂时屏蔽对camera的支持
//        if (pickerRepository.hasCameraInPickerPage()) {
//            return position - 1;
//        } else {
//            return position;
//        }
        return position;
    }

    private void finish() {

        if (pickerRepository.isStartInAllView()) {
            pickerView.finishActivityWithResult(pickerRepository.getSelectedImageList());
        } else {
            pickerView.finishActivity();
        }
    }

    private void onCheckStateChange(int position, Uri imageUri) {
        int selectedIndex = pickerRepository.getSelectedIndex(imageUri);
        PickerListItem.Image image = new PickerListItem.Image(imageUri, selectedIndex, pickerRepository.getPickerViewData());

//        if (selectedIndex == -1) {
//            pickerView.onCheckStateChange(pickerRepository);
//        } else {
//            pickerView.onCheckStateChange(position,image);
//        }
        pickerView.onCheckStateChange(position, image);
    }
}
